package com.xnyzc.lhy.mis.service.impl.cms.cashwithdrawal;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.finance.entity.bank.OaDBindAlipay;
import com.xnyzc.lhy.finance.entity.bank.OaDWithdrawalDetails;
import com.xnyzc.lhy.mis.config.AlipayConfig;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.result.cms.cashwithdrawal.OaDCashWithdrawalResults;
import com.xnyzc.lhy.mis.entity.result.cms.cashwithdrawal.OaDWithdrawalDetailsResults;
import com.xnyzc.lhy.mis.mapper.cashwithdrawal.OaDBindAlipayMapper;
import com.xnyzc.lhy.mis.mapper.cashwithdrawal.OaDCashWithdrawalMapper;
import com.xnyzc.lhy.mis.mapper.cashwithdrawal.OaDWithdrawalDetailsMapper;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.service.cms.cashwithdrawal.MisOaDCashWithdrawalService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 提现记录接口实现类
 *
 * @author zhaolijie
 * @date
 */
@Service
public class MisOaDCashWithdrawalServiceImpl implements MisOaDCashWithdrawalService {

    @Autowired
    private OaDCashWithdrawalMapper oaDCashWithdrawalMapper;

    @Autowired
    private OaDWithdrawalDetailsMapper oaDWithdrawalDetailsMapper;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaDBindAlipayMapper oaDBindAlipayMapper;


    /**
     * 获取提现列表数据
     *
     * @param oaDCashWithdrawalResults
     * @return
     */
    @Override
    public Rv getOaDCashWithdrawalResultsList(OaDCashWithdrawalResults oaDCashWithdrawalResults) {
        if (CheckUtil.objIsEmpty(oaDCashWithdrawalResults.getCurrent(), oaDCashWithdrawalResults.getSize())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        IPage<OaDCashWithdrawalResults> oaDCashWithdrawalResultsList = oaDCashWithdrawalMapper.getOaDCashWithdrawalResultsList(new Page(oaDCashWithdrawalResults.getCurrent(), oaDCashWithdrawalResults.getSize()), oaDCashWithdrawalResults);
        return Rv.wrap(oaDCashWithdrawalResultsList);
    }

    @Override
    public Rv getOaDWithdrawalDetailsList(OaDWithdrawalDetailsResults results) {
        if (CheckUtil.objIsEmpty(results.getCurrent(), results.getSize())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        JSONObject result = new JSONObject();
        //获取未处理的大小
        QueryWrapper<OaDWithdrawalDetails> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.ne(OaDWithdrawalDetails.APPLY_STATE,2);
        List<OaDWithdrawalDetails> list = oaDWithdrawalDetailsMapper.selectList(queryWrapper2);
        result.put("noHandleSize",list.size());
        //获取总金额
        BigDecimal totalAmount = new BigDecimal(0);
        List<OaDWithdrawalDetails> oaDWithdrawalDetailsList = oaDWithdrawalDetailsMapper.selectList(null);
        for (OaDWithdrawalDetails info:oaDWithdrawalDetailsList) {
            BigDecimal applyMoney = new BigDecimal(info.getApplyMoney());
            totalAmount = totalAmount.add(applyMoney);
        }
        result.put("totalAmount",totalAmount);
        result.put("totalRecord",oaDWithdrawalDetailsList.size());
        //创建分页器
        IPage<OaDWithdrawalDetails> iPage = new Page<>();
        iPage.setCurrent(results.getCurrent());
        iPage.setSize(results.getSize());
        //获取司机提现的数据
        QueryWrapper<OaDWithdrawalDetails> queryWrapper = new QueryWrapper<>();
        if(CheckUtil.objIsNotEmpty(results.getWithdrawalDetailsId())){
            queryWrapper.eq(OaDWithdrawalDetails.WITHDRAWAL_DETAILS_ID,results.getWithdrawalDetailsId());
        }
        if(CheckUtil.objIsNotEmpty(results.getDriverName())){
            queryWrapper.eq(OaDWithdrawalDetails.DRIVER_NAME,results.getDriverName());
        }
        if(CheckUtil.objIsNotEmpty(results.getAlipayNumber())){
            queryWrapper.eq(OaDWithdrawalDetails.ALIPAY_NUMBER,results.getAlipayNumber());
        }
        if(CheckUtil.objIsNotEmpty(results.getAlipayPhone())){
            queryWrapper.eq(OaDWithdrawalDetails.ALIPAY_PHONE,results.getAlipayPhone());
        }
        if(CheckUtil.objIsNotEmpty(results.getApplyState())){
            queryWrapper.eq(OaDWithdrawalDetails.APPLY_STATE,results.getApplyState());
        }
        if(CheckUtil.objIsNotEmpty(results.getCityId())){
            queryWrapper.eq(OaDWithdrawalDetails.CITY_ID,results.getCityId());
        }
        if(CheckUtil.objIsNotEmpty(results.getCityName())){
            queryWrapper.eq(OaDWithdrawalDetails.CITY_NAME,results.getCityName());
        }
        if(CheckUtil.objIsNotEmpty(results.getBeginTime()) && CheckUtil.objIsNotEmpty(results.getOverTime())){
            queryWrapper.between(OaDWithdrawalDetails.APPLY_TIME,results.getBeginTime(),results.getOverTime());
        }
        queryWrapper.orderByDesc(OaDWithdrawalDetails.APPLY_TIME);

        IPage<OaDWithdrawalDetails> iPageResult = oaDWithdrawalDetailsMapper.selectPage(iPage,queryWrapper);
        result.put("OaDWithdrawalDetailsList",iPageResult.getRecords());
        return Rv.wrap(result);
    }

    @Override
    public Rv getOneOrAllTransferAccounts(OaDWithdrawalDetailsResults param) {
        Long userId = TokenUtil.getTokenUserId();
        if (CheckUtil.objIsEmpty(userId)) {
            return Rv.error(EErrorCode.noAuth);
        }
        if (CheckUtil.objIsEmpty(param.getIsAllTransferAccounts())) {
            return Rv.error(EErrorCode.missingArg);
        }
        JSONObject jsonObject = new JSONObject();
        //成功的信息集合
        List<Long> successList = new ArrayList<>();
        //失败的信息集合
        List<Long> failList = new ArrayList<>();
        jsonObject.put("successSize",successList.size());
        jsonObject.put("successList",successList);
        jsonObject.put("failList",failList);
        jsonObject.put("successSize",successList.size());

        //首先判断是否全部转账
        if(param.getIsAllTransferAccounts() == 1){//是
            QueryWrapper<OaDWithdrawalDetails> detailsQueryWrapper = new QueryWrapper<>();
            List<Integer> list = new ArrayList<>();
            list.add(0);
            list.add(3);
            detailsQueryWrapper.in(OaDWithdrawalDetails.APPLY_STATE,list);
            //获取所有的未成功的的提现明细
            List<OaDWithdrawalDetails> oaDWithdrawalDetailsList = oaDWithdrawalDetailsMapper.selectList(detailsQueryWrapper);
            for(OaDWithdrawalDetails info:oaDWithdrawalDetailsList){
                //获取司机绑定支付宝信息
                QueryWrapper<OaDBindAlipay> oaDBindAlipayQueryWrapper = new QueryWrapper<>();
                oaDBindAlipayQueryWrapper.eq(OaDBindAlipay.DRIVER_ID,info.getDriverId());
                OaDBindAlipay oaDBindAlipay = oaDBindAlipayMapper.selectOne(oaDBindAlipayQueryWrapper);
                if(CheckUtil.objIsNotEmpty(oaDBindAlipay)){
                    //商家的订单号
                    String sOrderNo = info.getWithdrawalDetailsId().toString();
                    //申请金额
                    BigDecimal applyMoney = new BigDecimal(info.getApplyMoney());
                    //支付宝唯一用户id
                    String alipayUserId = oaDBindAlipay.getAlipayUserId();
                    //支付宝单笔转账实现方法以及返回结果
                    String result =AlipayConfig.getSingleTransfer3(sOrderNo,applyMoney,alipayUserId,null);
                    //处理结果与更新司机提现明细
                    if(CheckUtil.objIsEmpty(result)){
                        info.setApplyState(3);//设置失败状态
                        info.setWithdrawalRes("系统繁忙,请重试");
                        info.setUpdateUser(userId);
                        info.setUpdateTime(new Date());
                        oaDWithdrawalDetailsMapper.updateById(info);
                        failList.add(info.getWithdrawalDetailsId());
                        continue;
                    }
                    String[] res = result.split(",");
                    info.setWithdrawalRes(res[0]);
                    info.setPayNo(res[1]);
                    info.setPayTime(res[2]);
                    info.setApplyState(2);//设置成功状态
                    info.setUpdateUser(userId);
                    info.setUpdateTime(new Date());
                    oaDWithdrawalDetailsMapper.updateById(info);

                    successList.add(info.getWithdrawalDetailsId());
                }else {
                    failList.add(info.getWithdrawalDetailsId());
                }
            }
        }else {//否
            if (CheckUtil.objIsEmpty(param.getWithdrawalDetailsId())) {
                return Rv.error(EErrorCode.missingArg);
            }
            OaDWithdrawalDetails oaDWithdrawalDetails = oaDWithdrawalDetailsMapper.selectById(param.getWithdrawalDetailsId());
            if(CheckUtil.objIsEmpty(oaDWithdrawalDetails)){
                return Rv.error(EErrorCode.unOrder);
            }
            //获取司机绑定支付宝信息
            QueryWrapper<OaDBindAlipay> oaDBindAlipayQueryWrapper = new QueryWrapper<>();
            oaDBindAlipayQueryWrapper.eq(OaDBindAlipay.DRIVER_ID,oaDWithdrawalDetails.getDriverId());
            OaDBindAlipay oaDBindAlipay = oaDBindAlipayMapper.selectOne(oaDBindAlipayQueryWrapper);
            if(CheckUtil.objIsNotEmpty(oaDBindAlipay)){
                //商家的订单号
                String sOrderNo = oaDWithdrawalDetails.getWithdrawalDetailsId().toString();
                //申请金额
                BigDecimal applyMoney = new BigDecimal(oaDWithdrawalDetails.getApplyMoney());
                //支付宝唯一用户id
                String alipayUserId = oaDBindAlipay.getAlipayUserId();
                //支付宝单笔转账实现方法以及返回结果
                String result =AlipayConfig.getSingleTransfer3(sOrderNo,applyMoney,alipayUserId,null);
                //处理结果与更新司机提现明细
                if(CheckUtil.objIsEmpty(result)){
                    oaDWithdrawalDetails.setApplyState(3);//设置失败状态
                    oaDWithdrawalDetails.setUpdateUser(userId);
                    oaDWithdrawalDetails.setUpdateTime(new Date());
                    oaDWithdrawalDetailsMapper.updateById(oaDWithdrawalDetails);
                    return Rv.error(EErrorCode.GET_PAY_INFO_ERROR);
                }
                String[] res = result.split(",");
                oaDWithdrawalDetails.setWithdrawalRes(res[0]);
                oaDWithdrawalDetails.setPayNo(res[1]);
                oaDWithdrawalDetails.setPayTime(res[2]);
                oaDWithdrawalDetails.setApplyState(2);//设置成功状态
                oaDWithdrawalDetails.setUpdateUser(userId);
                oaDWithdrawalDetails.setUpdateTime(new Date());
                oaDWithdrawalDetailsMapper.updateById(oaDWithdrawalDetails);

                successList.add(oaDWithdrawalDetails.getWithdrawalDetailsId());
            }else {
                return Rv.error(EErrorCode.alipayNoBind);
            }
        }
        jsonObject.put("successSize",successList.size());
        jsonObject.put("successList",successList);
        jsonObject.put("failList",failList);
        jsonObject.put("successSize",successList.size());
        //重置集合
        successList.clear();
        failList.clear();

        return Rv.wrap(jsonObject);
    }

    /**
     * 获取字典信息
     *
     * @return
     */
    @Override
    public Rv getSysDict() {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "cash_withdrawal");
        List<OaSysDict> oaSysDicts = oaSysDictMapper.selectList(queryWrapper);
        return Rv.wrap(oaSysDicts);
    }

    /**
     * 导出提现记录
     *
     * @param oaDCashWithdrawal
     * @return
     */
    @Override
    public Rv exportOaDCashWithdrawalResultsList(OaDCashWithdrawalResults oaDCashWithdrawal) {
        String withdrawalNumber = oaDCashWithdrawal.getWithdrawalNumber();
        String cityCode = oaDCashWithdrawal.getCityCode();
        List<String> cityCodes = oaDCashWithdrawal.getCityCodes();
        String driverName = oaDCashWithdrawal.getDriverName();
        String withdrawalProgress = oaDCashWithdrawal.getWithdrawalProgress();
        Date beginTime = oaDCashWithdrawal.getBeginTime();
        Date overTime = oaDCashWithdrawal.getOverTime();
        List<OaDCashWithdrawalResults> dCashWithdrawalResults = oaDCashWithdrawalMapper.exportOaDCashWithdrawalResultsList(
                withdrawalNumber,
                cityCode,
                cityCodes,
                driverName,
                withdrawalProgress,
                beginTime,
                overTime
        );
        return Rv.wrap(dCashWithdrawalResults);
    }


}
